package com.qire.manhua.view.comicReader.renderer;

import android.graphics.Bitmap;

import androidx.annotation.Nullable;

import com.qire.manhua.view.comicReader.renderer.download.ComicPictureDownloader;


/**
 * 漫画图片池，用于管理资源与图片分离，管理图片的下载、缓存、释放等。
 * 是图片资源与缓存对接的中间层
 */
public class ComicPicturePool implements IResourcePool {

    public static final ComicPicturePool POOL = new ComicPicturePool();

    private final PicturePoolExecutor taskExecutor = new PicturePoolExecutor();

    private final IResourceCache resourceCache = ComicPictureCache.CACHE;

    private final IDownloader downloader = new ComicPictureDownloader();

    private ComicPicturePool() { }

    @Override
    public boolean sendPictureRequest(PictureResource pictureResource, IPictureLoader pictureLoader) {
        PictureLoadTask task = new PictureLoadTask(pictureResource, pictureLoader);
        if(taskExecutor.existInWaitQueue(task)) {
            return true;
        }
        taskExecutor.execute(task);
        return false;
    }

    @Override
    public boolean exitRequestEarly(PictureResource pictureResource) {
        return taskExecutor.cancelTask(pictureResource);
    }

    /**
     * 图片加载任务，每一个资源请求图片都会发送一个图片加载任务。
     */
    private class PictureLoadTask implements Runnable {

        private final PictureResource pictureResource;
        private final IPictureLoader pictureLoader;

        private PictureLoadTask(PictureResource pictureResource, IPictureLoader pictureLoader) {
            this.pictureResource = pictureResource;
            this.pictureLoader = pictureLoader;
        }

        @Override
        public void run() {
            /***************************************************
             * 1.由于 sendPictureRequest 时只检查了等待队列，所以存在于工作队列中的任务并未检查，
             *   所以为防止重复下载，则需要判断是否已经下载完成;
             * 2.从缓存中拿出图片,如果存在则加载到资源中；
             * 3.如果不存在则从网络下载图片。
             ***************************************************/

            if(pictureResource.canDrawn()) {
                return;
            }

            String uri = pictureResource.uri;

            Bitmap bitmap = resourceCache.getBitmapFromCache(uri);

            if(bitmap == null) {
                byte[] data = downloader.download(uri, pictureLoader);
                bitmap = resourceCache.saveBitmapToCache(uri, data);
            }

            pictureLoader.loadBitmap(bitmap);
        }

        @Override
        public boolean equals(@Nullable Object obj) {
            if(obj == null) {
                return false;
            }

            if(obj instanceof PictureLoadTask) {
                PictureLoadTask task = (PictureLoadTask) obj;
                return task.pictureResource.equals(pictureResource);
            }

            if(obj instanceof PictureResource) {
                PictureResource res = (PictureResource) obj;
                return res.equals(pictureResource);
            }

            return super.equals(obj);
        }
    }
}